﻿using Developer.Core.FrameWork.ClusterLoadBalance.Service;
using Developer.Core.FrameWork.RegisterCenter.Model;
using System;
using System.Collections.Generic;
using System.Text;

namespace Developer.Core.FrameWork.ClusterLoadBalance.Impl
{
    /// <summary>
    /// 加权随机算法
    /// </summary>
    public class RandomLoadBalance : AbstractLoadBalance
    {
        private readonly Random random = new Random();


        public override ServiceNode DoSelect(IList<ServiceNode> serviceUrls,string serviceName)
        {
            int length = serviceUrls.Count;
            int totalWeight = 0;
            bool sameWeight = true;
            for (int i = 0; i < length; i++)
            {
                int weight = GetWeight();
                totalWeight += weight;
                if (sameWeight && i > 0 && weight != GetWeight())
                    sameWeight = false;
            }

            if (totalWeight > 0 && !sameWeight)
            {
                int offset = random.Next(totalWeight);
                for (int i = 0; i < length; i++)
                {
                    offset -= GetWeight();
                    if (offset < 0)
                        return serviceUrls[i];
                }
            }

            return serviceUrls[random.Next(length)];
        }
    }
}
